package com.jxl.springboot.game.utils;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期转换工具类
 *
 * @author 江雪林
 * @create 2021-03-19
 */
public class DateUtils {
    /**
     * 将Date 转换成日期格式字符串
     *
     * @param date    Date
     * @param pattern 日期格式
     * @return
     */
    public static String toString(Date date, String pattern) {
        if (date == null)
            throw new IllegalArgumentException("date is null");
        if (pattern == null)
            throw new IllegalArgumentException("pattern is null");
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * 将日期字符串转换成Date
     *
     * @param strDate 日期字符串
     * @param pattern 日期格式
     * @return
     */
    public static Date toDate(String strDate, String pattern) {
        if (strDate == null)
            throw new IllegalArgumentException("date is null");
        if (pattern == null)
            throw new IllegalArgumentException("pattern is null");
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 获取当前时间的字符串 yyyyMMddHHmmss
     *
     * @return
     */
    public static String getNowDateStr() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int min = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        StringBuffer buffer = new StringBuffer();
        buffer.append(year);
        buffer.append(month);
        buffer.append(day);
        buffer.append(hour);
        buffer.append(min);
        buffer.append(second);
        return buffer.toString();
    }

    /**
     * 获取当前时间的字符串,使用 分隔符分隔
     * @param joinStr 分隔符
     * @return
     */
    public static String getNowDateStr(String joinStr) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int min = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        StringBuffer buffer = new StringBuffer();
        buffer.append(year+joinStr);
        buffer.append(month+joinStr);
        buffer.append(day+joinStr);
        buffer.append(hour+joinStr);
        buffer.append(min+joinStr);
        buffer.append(second+joinStr);
        return buffer.toString();
    }
}
